#include <cserver/restapi.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/log/trivial.hpp>
#include <boost/format.hpp>
#include <pqxx/transaction.hxx>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/common/deluser";

	void del_user(Request& req, pqxx::connection& dbconn, SessionContext& sctx, const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto sessionid = req.getCookie("sessionid");

		StreamGroup sg(req, 4096);
		boost::property_tree::ptree ptree;
		read_json(sg.fin, ptree);
		auto account = ptree.get<std::string>("account", "");

		std::string current_account, userid;
		bool is_admin = false;
		{
			std::lock_guard<std::mutex> guard(sctx.mutex);
			auto pos = sctx.activeSessions.find(sessionid);
			// assert( pos != master.sessions.activeSessions.end());
			current_account = pos->second;
			is_admin = sctx.user_info.find(current_account)->second.role == "admin";

			auto itr = sctx.user_info.find(account);
			if (itr != sctx.user_info.end())
				userid = itr->second.userid;
		}

		if (!is_admin || account == current_account)
		{
			response_error(sg.fout, 403, "ErrPermission", "PermissionDenied", req);
			return;
		}
		if (userid.empty()){
			response_error(sg.fout, 400, "ErrParameter", "AccountNotFound", req);
			return;
		}

		{
			std::lock_guard<std::mutex> guard(sctx.mutex);
			for (auto itr = sctx.activeSessions.begin(); itr != sctx.activeSessions.end();){
				if (itr->second == account)
					itr = sctx.activeSessions.erase(itr);
				else ++itr;
			}
			sctx.user_info.erase(account);
		}
		pqxx::work w(dbconn);
		w.prepared("delsession")(userid).exec();
		w.prepared("deluser")(userid).exec();
		w.commit();

		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";
		sg.fout << boost::format(R"({
"func":"deluser",
"args":{"account":%1%},
"ret":{"success":true, "message":""}
})") 
			% escape_string(account) ;
		if (!callback.empty()) sg.fout << ")";

	}

}
static CommandAddHelper k_registerHandler("POST", webcmd::K_this_command, &webcmd::del_user, {"admin"});
}



